<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
            v-model="searchForm.username"
            clearable
            placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getUserList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button plain type="primary" @click="dialogVisible = true;">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定要批量删除吗?" @confirm="delHandle(null)">
          <el-button slot="reference" :disabled="delIsAccess" type="danger">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>

    </el-form>

    <el-table
        ref="multipleTable"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="用户ID"
          prop="id"
          width="80">
      </el-table-column>
      <el-table-column
          label="用户名"
          prop="username"
          width="200">
      </el-table-column>
      <el-table-column
          label="个人介绍"
          prop="des"
          show-overflow-tooltip>
      </el-table-column>
      <el-table-column
          label="用户状态"
          prop="status"
          width="120"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" size="large" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status === 0" size="large" type="danger">封禁</el-tag>
        </template>
      </el-table-column>

      <el-table-column
          label="操作"
          prop="icon"
          width="210"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm
                  title="您确定要重置这个用户吗?初始密码：123456"
                  @confirm="resetUser(scope.row.id)"
          >
            <el-button slot="reference"  type="text">重置用户</el-button>
          </el-popconfirm>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm
              title="您确定要删除这个用户吗?"
              @confirm="delHandle(scope.row.id)"
          >
            <el-button slot="reference" type="text">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        :current-page="current"
        :page-size="size"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
    </el-pagination>

    <el-dialog
        :visible.sync="dialogVisible"
        title="新增用户"
        width="600px">
      <el-form ref="addUserModel" :model="addUserModel" :rules="addUserRule" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserModel.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserModel.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="repassword">
          <el-input v-model="addUserModel.repassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="des">
          <el-input v-model="addUserModel.des" :autosize="{minRows: 2, maxRows: 6}" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" @click="submitForm('addUserModel')">新增</el-button>
          <el-button @click="resetForm('addUserModel')">重置</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>

    <el-dialog
            :visible.sync="dialogEditVisible"
            title="编辑用户"
            width="600px">
      <el-form ref="editForm" :model="editForm" :rules="editUserRule" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="repassword">
          <el-input v-model="editForm.repassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="des">
          <el-input v-model="editForm.des" :autosize="{minRows: 2, maxRows: 6}" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="状态"  prop="status" label-width="100px">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" @click="editSubmit('editForm')">更新</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    const repassAuth = (rule, value, callback) => {
      if (value !== this.addUserModel.password)
        callback(new Error('两次密码输入不一致'))
      else
        callback()
    };

    const editRepassAuth = (rule, value, callback) => {
      if (value !== this.editForm.password)
        callback(new Error('两次密码输入不一致'))
      else
        callback()
    };

    const authPassword = (rule, value, callback) => {
      if(value.length > 0 && value.length < 6)
        callback(new Error('输入的密码过短!'))
      else if(value.length > 24)
        callback(new Error('输入的密码过长!'))
      else
        callback()
    }

    return {
      searchForm: {
        username: ''
      },
      editForm: {
        id: '',
        username: '',
        password: '',
        repassword: '',
        des: '',
        status: 1
      },
      delIsAccess: true,
      dialogVisible: false,
      dialogEditVisible: false,
      tableData: [],
      multipleSelection: [],
      current: 1,
      size: 5,
      total: 0,

      addUserModel: {
        username: '',
        password: '',
        repassword: '',
        des: ''
      },
      addUserRule: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 6, max: 24, message: '用户名长度在 6 - 24 个字符之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '用户名最小需要 6 位', trigger: 'blur'}
        ],
        repassword: [
          {required: true, message: '请再次输入密码', trigger: 'blur'},
          {validator: repassAuth, trigger: 'blur'}
        ]
      },

      editUserRule: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 6, max: 24, message: '用户名长度在 6 - 24 个字符之间', trigger: 'blur'}
        ],
        password: [
          {validator: authPassword, trigger: 'blur'}
        ],
        repassword: [
          {validator: editRepassAuth, trigger: 'blur'}
        ]
      },

    }
  },

  created() {
    this.getUserList()
  },

  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleClose() {
      this.resetForm('editForm')
    },
    handleSizeChange(val) {
      this.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getUserList()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          if (this.dialogVisible === true)
            this.dialogVisible = false

          this.$http.post('/sys/user/save', this.addUserModel).then(res => {
            if(res.data.code === 200) {
              this.$message({
                showClose: true,
                message: '添加用户成功',
                type: 'success',
                onClose: () => {
                  this.getUserList()
                }
              })
            } else {
              this.$message.error(this.data.msg)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editSubmit(editForm) {
      this.$refs[editForm].validate((valid) => {
        if (valid) {

          if (this.dialogEditVisible === true)
            this.dialogEditVisible = false

          this.$http.post('/sys/user/update', this.editForm).then(res => {
            if(res.data.code === 200) {
              this.$message({
                showClose: true,
                message: '编辑用户成功',
                type: 'success',
                onClose: () => {
                  this.getUserList()
                }
              })
            } else {
              this.$message.error(this.data.msg)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetUser(id) {

      this.$http.post('/sys/user/reset', id).then(res => {
        if(res.data.code === 200) {
          this.$message({
            showClose: true,
            message: '重置用户成功',
            type: 'success',
            onClose: () => {
              this.getUserList()
            }
          })
        } else {
          this.$message.error(this.data.msg)
        }
      })
    },
    handleSelectionChange(val) {
      console.log("勾选")
      console.log(val)
      this.multipleSelection = val;
      this.delIsAccess = val.length === 0
    },
    delHandle(id) {
      var ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      this.$http.post("/sys/user/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose:() => {
            this.getUserList()
          }
        });
      })
    },
    editHandle(id) {
      this.editForm.id = id
      this.$http.get('/sys/user/info/' + id).then(res => {
        const user = res.data.data;
        this.editForm.username = user.username
        this.editForm.des = user.des
        this.editForm.status = user.status
      })
      this.dialogEditVisible = true;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getUserList() {
      this.$http.get('/sys/user/list', {
        params: {
          username: this.searchForm.username,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.data.records
        this.size = res.data.data.size
        this.total = res.data.data.total
        this.current = res.data.data.current
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>
